package cn.chowx.myjfinal.system.model;

import java.util.List;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;

import cn.chowx.myjfinal.common.BaseModel;
import cn.chowx.myjfinal.common.TableName;
import cn.chowx.myjfinal.help.PageHelp;

/**
 * 系统角色
 * @author zcqshine
 *
 */
@SuppressWarnings("serial")
public class SysRole extends BaseModel<SysRole> {
	public static final SysRole DAO = new SysRole();
	
	/**
	 * 获取该角色下有效的资源
	 * @return
	 */
	public List<SysAction> getActionsByRoleId(){
		return SysAction.DAO.find("select * from sys_action a where id in (select actionId from sys_role_action where roleId = ? and `status`=1) order by a.order ", get("id"));
	}
	
	/**
	 * 获取该角色下的用户
	 * @return
	 */
	public List<SysUser> getUserByRoleId(){
		return SysUser.DAO.find("select * from sys_user where id in (select userId from sys_user_role where roleId = ?)",get("id"));
	}
	
	/**
	 * 分页查询,搜索
	 * @param pageHelp
	 * @return
	 */
	public Page<Record> findRecordList(PageHelp pageHelp){
		String select = "select A.*, B.roleName parentName";
		StringBuilder sb = new StringBuilder("FROM sys_role A, sys_role B where A.parentId = B.id ");
		sb.append(PageHelp.buildSearchSQL(pageHelp, "A"));
		sb.append(" order by id asc");
		return Db.paginate(pageHelp.getPageNum(), pageHelp.getRows(), select, sb.toString());
	}
	
	/**
	 * 获取角色的键值对. id:name;id:name;... 的字符串
	 * @return String
	 */
	public String getSelectKeyValue(){
		List<SysRole> roles = findList(1);
		StringBuilder sb = new StringBuilder();
		if(roles != null){
			for(SysRole role : roles){
				sb.append(role.getInt("id")).append(":")
				.append(role.getStr("roleName")).append(";");
			}
			if(sb != null){
				sb = sb.deleteCharAt(sb.lastIndexOf(";"));
			}
		}
		return sb.toString();
	}
	
	/**
	 * 根据状态查询角色
	 * @param status 角色状态, 1:有效, 0-无效
	 * @return
	 */
	public List<SysRole> findList(int status){
		String sql = "select * from " + TableName.SysRole.getTableName()  + " where `status` = " + status;
		return find(sql);
	}
	
	
}
